package com.lechi.web.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.lechi.web.common.annotation.Log;
import com.lechi.web.common.config.LeChiConfig;
import com.lechi.web.common.core.controller.BaseController;
import com.lechi.web.common.core.domain.AjaxResult;
import com.lechi.web.common.core.domain.entity.SysUser;
import com.lechi.web.common.core.domain.model.LoginUser;
import com.lechi.web.common.core.page.TableDataInfo;
import com.lechi.web.common.enums.BusinessType;
import com.lechi.web.common.utils.SecurityUtils;
import com.lechi.web.common.utils.file.FileUploadUtils;
import com.lechi.web.common.utils.file.FileUtils;
import com.lechi.web.constants.AppCmdConstants;
import com.lechi.web.service.IIotSourceFileService;
import com.lechi.web.system.domain.IotSourceFile;
import com.lechi.web.vo.IotSourceFileQueryVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 升级包管理Controller
 *
 * @author yangguang
 * @date 2024 -07-10
 */
@RestController
@RequestMapping("/iot/app/file")
@RequiredArgsConstructor
public class IotSourceFileController extends BaseController {


    private final IIotSourceFileService iotSourceFileService;


    private final LeChiConfig leChiConfig;

    /**
     * 查询升级包管理列表
     *
     * @param iotSourceFileQueryVo the iot source file query vo
     * @return the table data info
     */
    @GetMapping("/list")
    //    @PreAuthorize("@ss.hasPermi('iot:file:query')")
    public TableDataInfo list(IotSourceFileQueryVo iotSourceFileQueryVo) {
        startPage();
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        IotSourceFile iotSourceFile = new IotSourceFile();
        BeanUtils.copyProperties(iotSourceFileQueryVo, iotSourceFile);
        if (!user.isAdmin()) {
            iotSourceFile.setCreateBy(user.getUserName());
        }
        if ("doc".equalsIgnoreCase(iotSourceFile.getFileType())) {
            return getDataTable(iotSourceFileService.selectIotDocFileList(iotSourceFile));
        }
        return getDataTable(iotSourceFileService.selectIotSourceFileList(iotSourceFile));
    }

    /**
     * 查询升级包管理列表
     *
     * @param iotSourceFileQueryVo the iot source file query vo
     * @return the table data info
     */
    @GetMapping("/screen/list")
    //    @PreAuthorize("@ss.hasPermi('iot:file:query')")
    public TableDataInfo screen(IotSourceFileQueryVo iotSourceFileQueryVo) {
        startPage();
        IotSourceFile iotSourceFile = new IotSourceFile();
        BeanUtils.copyProperties(iotSourceFileQueryVo, iotSourceFile);
        List<IotSourceFile> list = iotSourceFileService.selectIotScreenshotFileList(iotSourceFile);
        return getDataTable(list);
    }


    /**
     * 获取升级包管理详细信息
     *
     * @param id the id
     * @return the info
     */
    @GetMapping(value = "/{id}")
    //    @PreAuthorize("@ss.hasPermi('iot:file:query')")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(iotSourceFileService.selectIotSourceFileById(id));
    }


    /**
     * 素材上传请求
     *
     * @param sourceName the source name
     * @param fileType   the file type
     * @param file       the file
     * @return the ajax result
     */
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    //    @PreAuthorize("@ss.hasPermi('iot:file:puload')")
    public AjaxResult uploadFile(@RequestParam("sourceName") String sourceName, @RequestParam("fileType") String fileType, @RequestPart("file") MultipartFile file) {
        try {
            String filePath = LeChiConfig.getAppUploadPath();
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = leChiConfig.getNginxip() + fileName;
            IotSourceFile iotSourceFile = new IotSourceFile();
            iotSourceFile.setSourceName(sourceName);
            iotSourceFile.setCreateBy(SecurityUtils.getUsername());
            iotSourceFile.setFileName(file.getOriginalFilename());
            final BigDecimal divide = BigDecimal.valueOf(file.getSize()).divide(BigDecimal.valueOf(1048576), 2, RoundingMode.HALF_UP);
            iotSourceFile.setFileSize(divide.doubleValue());
            iotSourceFile.setNewFileName(FileUtils.getName(fileName));
            iotSourceFile.setFileType(fileType);
            iotSourceFile.setDownLoadUrl(url);
            iotSourceFile.setApkMd5(DigestUtil.md5Hex(new File(filePath + File.separator + iotSourceFile.getNewFileName())));
            iotSourceFile.setStatus(AppCmdConstants.UN_PUBLISH);
            iotSourceFileService.insertIotSourceFile(iotSourceFile);
            return AjaxResult.success(url);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除资源文件管理
     *
     * @param ids the ids
     * @return the ajax result
     */
    @Log(title = "资源文件管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    //    @PreAuthorize("@ss.hasPermi('iot:file:remove')")
    public AjaxResult remove(@PathVariable Long[] ids) {

        CompletableFuture.runAsync(() -> {
            String filePath = LeChiConfig.getAppUploadPath();
            Arrays.stream(ids).forEach(id -> {
                IotSourceFile iotSourceFile = iotSourceFileService.selectIotSourceFileById(id);
                File file = new File(filePath + "/" + iotSourceFile.getNewFileName());
                if (file.exists()) {
                    file.delete();
                }
            });
        });

        return toAjax(iotSourceFileService.deleteIotSourceFileByIds(ids));
    }
}
